package jl.com.util;

import jl.com.aliyun.check.AliYunOSS;
import jl.com.aliyun.config.ConfigProperties;
import jl.com.service.ArticeSpiderService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmUtil {
    private final static Logger log = LoggerFactory.getLogger(HtmUtil.class);

    private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>";// 定义script的正则表达式
    private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>";// 定义style的正则表达式
    private static final String regEx_html = "<[^>]+>";// 定义HTML标签的正则表达式
    private static final String regEx_space = "\\s*|\t|\r|\n";//定义空格回车换行符
    private static final String regEx_body = ".*<body[^>]*?>";
    private static final String regEx_head = "<head[^>]*?>[\\s\\S]*?<\\/head>";// 定义head的正则表达式
    private static final String regEx_link = "<link[^>]*?>";// 定义link的正则表达式


    public static String rtnHtml(String html){
        String htmlStr = "";
        /*String style = sytle(html());   //获取sytle内样式
        System.out.println("style=="+style);*/
//        htmlStr = delHTMLTag(html());   //根据正则表达式截取html元素
        htmlStr = delHTMLTag(html);   //根据正则表达式截取html元素
        String result = htmlStr;
//        System.out.println("delHTMLTag=="+htmlStr);
//        List<String> strings = rtnImgSrc(htmlStr);//截取html元素中的src路径
//        String response = updateSrcAliyun(strings,htmlStr);  //将原图片src路径替换成阿里云路径
//        System.out.println("show=="+response);
//        response = addOnclic(response);     //添加点击方法addBtnShow
//        System.out.println("addOnclic=="+response);
        /*response = addBtn("(i?)(\\<div[^>]*?>)((.*?\\s)[^\\>]+\\>)",response);      //添加编辑选项
        response = addBtn("(i?)(\\<p[^>]*?>)((.*?\\s)[^\\>]+\\>)",response);      //添加编辑选项*/
//        System.out.println("addBtn=="+response);
//        response = rtnAddMethod(response);      //修改方法为含递增方法
//        System.out.println("rtnAddMethod=="+response);
        return result;
    }

    /**
     * 获取body内容
     * @param htmlStr
     * @return
     */
    public static String rtnBody(String  htmlStr){
//        String htmlStr = "<html><head></head><body><li></li>11111</body></html>";
        Pattern p_body = Pattern.compile(regEx_body, Pattern.CASE_INSENSITIVE);
        Matcher m_body = p_body.matcher(htmlStr);
        htmlStr = m_body.replaceAll(""); // 过滤body标签
        htmlStr = htmlStr.replaceAll("</body>","");
        htmlStr = htmlStr.replaceAll("<head>","");
        htmlStr = htmlStr.replaceAll("</head>","");
        htmlStr = htmlStr.replaceAll("<html>","");
        htmlStr = htmlStr.replaceAll("</html>","");
//        System.out.println(htmlStr);
        return htmlStr;
    }

    /**
     * 去除a标签的href
     */
    public static String cleanHref(String str){
        Pattern p = Pattern.compile("<a[^<]*?>");
        Matcher m = p.matcher(str);
        //去除标签
        String result = m.replaceAll("<a>");
//        System.out.println(response);
        return result;

    }
    /**
     * 添加点击方法addBtnShow
     * @param str
     * @return
     */
    public static String addOnclic(String str){
        String ing =  "(i?)(\\<div[^>]*?|<img[^>]*?|<p[^>]*?)((.*?\\s)[^\\>]+\\>)";
        Pattern p_script = Pattern.compile(ing, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(str);
        str = m_script.replaceAll("$2 @click=\"addBtnShow(RESULTA,\\$event)\" :style=\"contentStyle[RESULTA]\" $3"); // 过滤script标签
        /*System.out.println("str1:"+str);
        str = rtnAddMethod(str);
        System.out.println("str2:"+str);*/
        return  str;
    }

    /**
     * 添加编辑选项
     * @param regex
     * @param str
     * @return
     */
    public  static String addBtn(String regex,String str){
        //"(i?)(\\<p[^>]*?>)((.*?\\s)[^\\>]+\\>)"
        String ing = regex;
        Pattern p_script = Pattern.compile(ing, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(str);
        str = m_script.replaceAll("$2 <div class=\"change-wrap\"  v-if = \"btnPrise[1]\">\n" +
                "                <div class=\"delete\" @click=\"deleteInfo(1)\">删除</div>\n" +
                "                <div class=\"add-text\" @click=\"changeText(1)\">{{ item.type === 1 ? '修改文字' : '添加文字' }}</div>\n" +
                "                <div class=\"add-pic\" @click=\"upPic(1, 1)\">添加图片</div>\n" +
                "            </div> $3");
        return str;
    }

    /**
     * 修改方法为含递增方法
     * @return
     */
    public static String rtnAddMethod(String str){
//    public void rtnAddMethod(){
        String result = "";
        String input = "RESULTA";
//        String str = "<div @click=\"addBtnShow(RESULTA)\"></div><div @click=\"addBtnShow(RESULTA)\"></div><div @click=\"addBtnShow(RESULTA)\"></div><div @click=\"addBtnShow(RESULTA)\"></div>dddddddd";
        Pattern p = Pattern.compile(input);
        Matcher m = p.matcher(str);
        int count = 0;
        result = str;
        while(m.find())
        {
           /* System.out.println("---开始的位置---m.start() = "+m.start());
            System.out.println("---开始的位置---m.end() = "+m.end());*/
            StringBuffer buffer = new StringBuffer(result);
            if ("".equals(result))
                continue;
            if(count ==0){
                buffer.replace(m.start(), m.end(), ++count+"");
                result = buffer.toString();
            }else if(count<10){
                buffer.replace(m.start(), m.end()-6, ++count+"");
                result = buffer.toString();
            } else if(count<100){
                buffer.replace(m.start(), m.end()-5, ++count+"");
                result = buffer.toString();
            }else if(count<1000){
                buffer.replace(m.start(), m.end()-4, ++count+"");
                result = buffer.toString();
            }else if(count<10000){
                buffer.replace(m.start(), m.end()-3, ++count+"");
                result = buffer.toString();
            }
        }
        result = result.replaceAll("RESULT","");//ESULTA
        result = result.replaceAll("RESUL","");//SULTA
        result = result.replaceAll("RESU","");//SULTA
        result = result.replaceAll("RES","");//SULTA

//        System.out.println(response);
        return result;
    }

    /**
     * 测试图片上传
     */
    @Test
    public void imgTest(){
        String img = "https://mp.weixin.qq.com/mp/readtemplate?t=pages/video_player_tmpl&amp;action=mpvideo&amp;auto=0&amp;vid=wxv_1328148541432315909";
        //将图片转换成base64
        String base64 =  ImgUtil.imgBase64(img);
        base64 = "data:image/jpeg;base64,"+base64;
        //将base64编码的图片上传至阿里云并返回图片链接
       String  path = AliYunOSS.uploadImage(ConfigProperties.resource.getString("fileName")+System.currentTimeMillis()+".jpg",base64);
        System.out.println(path);

    }

    /**
     * 将原图片src路径替换成阿里云路径(抓取图片)
     * @param strings
     * @param html
     * @return
     */
    public  static Map<String,Object>  updateSrcAliyun(List<String> strings,String html){
        List<String> lists = new ArrayList<>();
        for (String string : strings) {
            if (!"".equals(string) && string.indexOf("http") != -1){
                String path = "";
                if (string.indexOf("zhangsan-oss") != -1){//判断图片是否存在阿里云,有的话不上传
                    path = string;
                }else {
                    //将图片转换成base64
                    String base64 =  ImgUtil.imgBase64(string);
                    base64 = "data:image/jpeg;base64,"+base64;
                    //将base64编码的图片上传至阿里云并返回图片链接
                    path = AliYunOSS.uploadImage(ConfigProperties.resource.getString("fileName")+System.currentTimeMillis()+".jpg",base64);
                }

                lists.add(path);
                html =html.replace(string,path);
            }
        }
//        html = html.replaceAll("crossorigin","crossoriginTwo");
//        html = html.replaceAll("src","data-src");
//        html = html.replaceAll("data-data-src","src");
        html = html.replaceAll("data-src","src");

        Map<String,Object> map = new HashMap<>();
        map.put("html",html);
        map.put("srcs",lists);
        return map;
    }


    /**
     * 这个方法是修复已抓取的文章内背景图片没处理的问题
     * 将原图片src路径替换成阿里云路径(抓取图片)
     * @param strings
     * @param html
     * @return
     */
    public  static Map<String,Object>  updateSrcAliyunTo(List<String> strings,String html){
        List<String> lists = new ArrayList<>();
        for (String string : strings) {
            if (!"".equals(string) && string.indexOf("http") != -1){
                String path = "";
                if (string.indexOf("zhangsan-oss") != -1){//判断图片是否存在阿里云,有的话不上传
                    path = string;
                }else {
                    //将图片转换成base64
                    String base64 =  ImgUtil.imgBase64(string);
                    base64 = "data:image/jpeg;base64,"+base64;
                    //将base64编码的图片上传至阿里云并返回图片链接
                    path = AliYunOSS.uploadImage(ConfigProperties.resource.getString("fileName")+System.currentTimeMillis()+".jpg",base64);
                }

                lists.add(path);
                html =html.replace(string,path);
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("html",html);
        map.put("srcs",lists);
        return map;
    }

    /**
     * 将原图片src路径替换成阿里云路径(检测)
     * @param strings
     * @param html
     * @return
     */
    public  static Map<String,Object>  updateSrcAliyunCheck(List<String> strings,String html){
        List<String> lists = new ArrayList<>();
        for (String string : strings) {
            if (!"".equals(string) && string.indexOf("http") != -1){
                String path = "";
                if (string.indexOf("sydlspace") != -1){//判断图片是否存在阿里云,有的话不上传
                    path = string;
                }else {
                    //将图片转换成base64
                    String base64 =  ImgUtil.imgBase64(string);
                    base64 = "data:image/jpeg;base64,"+base64;
                    //将base64编码的图片上传至阿里云并返回图片链接
                    path = AliYunOSS.uploadImage("imgTest/"+System.currentTimeMillis()+".jpg",base64);
                }

                lists.add(path);
                html =html.replace(string,path);
            }
        }

        Map<String,Object> map = new HashMap<>();
        map.put("html",html);
        map.put("srcs",lists);


        return map;
    }

    /**
     * 截取html元素中的data_src路径
     * @param html
     * @return
     */
    public static List<String> rtnImgData_Src(String html){
        List<String> strings = StringUtil.getImgStcListTwo(html);
       /* for (String string : strings) {
            System.out.println(string);
        }*/
        return strings;
    }
    /**
     * 截取html元素中的src路径
     * @param html
     * @return
     */
    public static List<String> rtnImgSrc(String html){
        List<String> strings = StringUtil.getImgStcList(html);
        /*for (String string : strings) {
            System.out.println(string);
        }*/
        return strings;
    }

    /**
     *获取sytle内样式
     * @param html
     * @return
     */
    public static String sytle(String html){
        String style1 = "<style>";
        String style2 = "</style>";
        String ht = html.substring(html.indexOf(style1)+style1.length(),html.indexOf(style2));
        return ht;
    }
    /**
     *获取title内容
     * @param html
     * @return
     */
    public static String rtnTitle(String html){
//        String testStr = "12315<h2>show me</h2>sdsds";
        Pattern p = Pattern.compile(".*<h2.*>(.*)</h2>.*");
        Matcher m = p.matcher(html);
        String title = "";
        while(m.find()){
            title = m.group(1);
        }
        return title;
    }
    /**
     * 根据正则表达式截取html元素
     * @param htmlStr
     * @return
     */
    public static String delHTMLTag(String htmlStr) {
        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 过滤style标签

        Pattern p_head = Pattern.compile(regEx_head, Pattern.CASE_INSENSITIVE);
        Matcher m_head = p_head.matcher(htmlStr);
        htmlStr = m_head.replaceAll(""); // 过滤head标签

        Pattern p_link = Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE);
        Matcher m_link = p_link.matcher(htmlStr);
        htmlStr = m_link.replaceAll(""); // 过滤link标签

        Pattern p_body = Pattern.compile(regEx_body, Pattern.CASE_INSENSITIVE);
        Matcher m_body = p_body.matcher(htmlStr);
        htmlStr = m_body.replaceAll(""); // 过滤body标签
        htmlStr = htmlStr.replaceAll("</body>","");
        htmlStr = htmlStr.replaceAll("<!DOCTYPE html>","");
        htmlStr = htmlStr.replaceAll("<html>","");
        htmlStr = htmlStr.replaceAll("</html>","");
        htmlStr = htmlStr.replaceAll("\n","");
        return htmlStr.trim(); // 返回文本字符串
    }

    /**
     * url解码
     * @param str
     * @return
     */
    public static String getURLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return result;
    }
    /**
     * url编码
     * @param str
     * @return
     */
    public static String getURLCoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 从页面中提取背景图片的链接
     * 如：<section style="background-image: url(https://mmbiz.qpic.cn/mmbiz_png/Ljsdsmt=png);background-position;</section>
     * 结果：https://mmbiz.qpic.cn/mmbiz_png/Ljsdsmt=png
     * @param html
     * @return
     */
    public static List<String> getBackgroundImg(String html){
        Document jsoup = Jsoup.parse(html);
        Elements elements = jsoup.select("section");
        elements.addAll(jsoup.select("div"));
        List<String> imgs = new ArrayList<>();
        for (Element element : elements) {
            //从此标签内获取style内容如：<section style="background-image: url(https://mmbiz.qpic.cn/mmbiz_png/Ljsdsmt=png);background-position;
            //结果：background-image: url(https://mmbiz.qpic.cn/mmbiz_png/Ljsdsmt=png);background-position;
            String img = element.attr("style");
            if (img.indexOf("http") != -1){
                //获取中的链接：background-image: url(https://mmbiz.qpic.cn/mmbiz_png/Ljsdsmt=png);background-position;
                //结果:https://mmbiz.qpic.cn/mmbiz_png/Ljsdsmt=png
                imgs.add(img.substring(img.indexOf("(\"")+2,img.indexOf("\")")));
            }
        }
        return imgs;
    }

    /**
     * 视频背景图片url解码上传替换处理
     * @param html
     */
    public static String iframeImg(String html){
        Document jsoup = Jsoup.parse(html);
        Elements elements = jsoup.select("iframe");
        for (Element element : elements) {
            String img = element.attr("data-cover");
            String imgUrlCode = img;
            if (img.indexOf("http") != -1){
                //url解码
                img = HtmUtil.getURLDecoderString(img);
                //将图片转换成base64
                String base64 =  ImgUtil.imgBase64(img);
                base64 = "data:image/jpeg;base64,"+base64;
                //将base64编码的图片上传至阿里云并返回图片链接
                String  path = AliYunOSS.uploadImage(ConfigProperties.resource.getString("fileName")+System.currentTimeMillis()+".jpg",base64);
                //url编码
                path = HtmUtil.getURLCoderString(path);
                html = html.replace(imgUrlCode,path);
            }
        }
        return  html;
    }
}
